package tcp

import (
	"context"
	"errors"
	"fmt"
	"nprobe/core"
)

func NewTCPSenderGroup(
	ctx context.Context, name string, task *core.ProbeTask, maxPPSPerSender int, salts map[int][]byte, receiverCnt int,
) (*core.SenderGroup, error) {
	var senders []core.Sender

	targetCnt := len(task.DstIPs)
	targetCntPerSender := maxPPSPerSender / task.PPS
	if targetCntPerSender < 1 {
		return nil, errors.New("task PPS is too large")
	}

	senderCnt := (targetCnt + targetCntPerSender - 1) / targetCntPerSender
	for i := 0; i < senderCnt; i++ {
		lowBound := i * targetCntPerSender
		upBound := lowBound + targetCntPerSender
		var targets []string
		if upBound < targetCnt {
			targets = task.DstIPs[lowBound:upBound]
		} else {
			targets = task.DstIPs[lowBound:]
		}
		sender := NewTCPSender(ctx, fmt.Sprintf("%s-sender-%d", name, i), i, targets, task, salts, receiverCnt)
		senders = append(senders, sender)
	}

	return &core.SenderGroup{Ctx: ctx, Name: name + "-sender-group", Senders: senders}, nil
}
